<template>
  <v-container>
    <v-dialog
      v-model="dialog"
      :max-width="dialogWidth"
    >
      <v-card>
        <v-card-title>
          <span class="text-h3">
            {{ lanChar.ruleConfig.MCGroupRuleViewDialogTitle }}
          </span>
        </v-card-title>
        <v-divider />
        <v-divider />
        <v-divider />
        <v-divider />
        <v-card-text>
          <v-container class="text-h4 text--primary font-weight-medium">
            <v-row>
              <v-spacer />
              <v-btn
                v-if="mode === 'add'"
                class="mr-0"
                color="secondary"
                width="100"
                @click="confirmDialog(lanChar.ruleConfig.MCGroupRuleAddConfirm+groupRule.Name+'?', 'Group Rule:'+JSON.stringify(groupRule), applyAdd, {})"
              >
                {{ lanChar.operateAdd }}
              </v-btn>
              <v-btn
                v-if="mode === 'update'"
                class="mr-0"
                color="secondary"
                width="100"
                @click="confirmDialog(lanChar.ruleConfig.MCGroupRuleModConfirm+groupRule.Name+'?', 'Group Rule:'+JSON.stringify(groupRule), applyModify, {})"
              >
                {{ lanChar.operateApply }}
              </v-btn>
            </v-row>
            <v-divider class="mb-3" />
            <v-row
              dense
              align="center"
            >
              <v-col
                cols="12"
                sm="2"
              >
                <span>
                  {{ lanChar.ruleConfig.MCGroupRuleName }}
                </span>
              </v-col>
              <v-col
                cols="12"
                sm="10"
              >
                <v-text-field
                  v-model.trim="groupRule.Name"
                  solo-inverted
                  dense
                  :rules="[rules.required, rules.string]"
                  :hint="lanChar.ruleConfig.MCGroupRuleNameInputHint"
                  hide-details="auto"
                />
              </v-col>
            </v-row>
            <v-divider />
            <v-row
              dense
              align="center"
            >
              <v-col
                cols="12"
                sm="2"
              >
                <span>
                  {{ lanChar.ruleConfig.MCGroupRuleTcpUri }}
                </span>
              </v-col>
              <v-col
                cols="12"
                sm="10"
              >
                <v-text-field
                  v-model.trim="groupRule.ServerTcp.Uri"
                  solo-inverted
                  dense
                  :rules="[rules.tcpUri]"
                  :hint="lanChar.ruleConfig.MCGroupRuleTcpUriInputHint"
                  hide-details="auto"
                />
              </v-col>
            </v-row>
            <v-divider />
            <v-row
              dense
              align="center"
            >
              <v-col
                cols="12"
                sm="2"
              >
                <span>
                  {{ lanChar.ruleConfig.MCGroupRuleUdpUri }}
                </span>
              </v-col>
              <v-col
                cols="12"
                sm="10"
              >
                <v-text-field
                  v-model.trim="groupRule.ServerUdp.Uri"
                  solo-inverted
                  dense
                  :rules="[rules.udpUri]"
                  :hint="lanChar.ruleConfig.MCGroupRuleUdpUriInputHint"
                  hide-details="auto"
                />
              </v-col>
            </v-row>
            <v-divider />
            <v-row
              dense
              align="center"
            >
              <span>
                {{ lanChar.ruleConfig.MCGroupRuleClientLimit }}
              </span>
              <v-checkbox
                v-model="groupRule.ClientLimit"
                class="pl-5 mb-5"
                color="secondary"
                hide-details
                dense
                :label="groupRule.ClientLimit?lanChar.checkStatusYes : lanChar.checkStatusNo"
              />
            </v-row>
            <v-row
              dense
              align="center"
            >
              <v-col
                cols="12"
                sm="2"
              >
                <span>
                  {{ lanChar.ruleConfig.MCGroupRuleClientUri }}
                </span>
              </v-col>
              <v-col
                cols="12"
                sm="10"
              >
                <v-row
                  v-for="(viClient, iClient) in groupRule.Clients"
                  :key="iClient"
                  dense
                  align="center"
                >
                  <v-col
                    class="d-flex"
                    cols="12"
                    sm="10"
                  >
                    <v-text-field
                      v-model.trim="viClient.Uri"
                      solo-inverted
                      dense
                      :rules="[rules.tcpUdpUri]"
                      :hint="lanChar.ruleConfig.MCGroupRuleTcpUdpUriInputHint"
                      hide-details="auto"
                    />
                  </v-col>
                  <v-col
                    class="d-flex"
                    cols="12"
                    sm="2"
                  >
                    <v-select
                      v-model.trim="viClient.Role"
                      :items="roleItems"
                      :disabled="mode==='view'"
                      color="purple"
                      dense
                      outlined
                      hide-details
                      style="width: 10px"
                    />
                  </v-col>
                </v-row>
                <v-tooltip
                  v-if="mode !== 'view'"
                  top
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-btn
                      color="primary"
                      dark
                      width="100%"
                      v-bind="attrs"
                      v-on="on"
                      @click="addClientUri()"
                    >
                      <v-icon left>
                        mdi-plus-circle
                      </v-icon>
                      <span>{{ lanChar.ruleConfig.MCGroupRuleAddClientUriButtonDescp }}</span>
                    </v-btn>
                  </template>
                  <span>{{ lanChar.ruleConfig.MCGroupRuleAddClientUriButtonHint }}</span>
                </v-tooltip>
              </v-col>
            </v-row>
            <v-divider />
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            color="blue darken-1"
            text
            @click="dialog = false"
          >
            {{ lanChar.operateClose }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <material-snackbar-tip
      v-model="snackbarDescp.snackbar"
      :type="snackbarDescp.snackbarType"
      :timeout="snackbarDescp.snackbarTimeout"
      v-bind="{
        bottom: true,
        right: true
      }"
      :text="snackbarDescp.snackbarContent"
    />
    <alert-dialog
      v-model="alert.dialog"
      :title="alert.title"
      :msg="alert.msg"
    />
    <confirm-dialog
      v-model="confirm.dialog"
      :title="confirm.content.title"
      :msg="confirm.content.msg"
      :callback="confirm.operate.callback"
      :input="confirm.operate.input"
    />
  </v-container>
</template>

<script>
  import globalDef from '@/util/globals'
  import lan from '@/util/lan-char'
  import * as mcAxios from '@/util/mcaxios'
  export default {
    name: 'McGroupRuleViewDialog',
    props: {
      value: Boolean,
      input: Object,
    },
    data () {
      return {
        lanChar: lan.GetLan(),
        dialog: this.value,
        dialogWidth: 1000, // document.body.clientWidth ||
        groupRule: {
          Name: '',
          ServerTcp: {
            Role: 0,
            Uri: '',
          },
          ServerUdp: {
            Role: 0,
            Uri: '',
          },
          Clients: [],
          ClientLimit: false,
        },
        mode: 'add',
        updateCnt: 0,
        rules: {
          required: value => !!value || this.lanChar.checkRequired,
          counter: value => value.length <= 20 || 'Max 20 characters',
          email: value => {
            const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            return pattern.test(value) || this.lanChar.checkInvalidEMail
          },
          string: value => {
            const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))$/
            return pattern.test(value) || this.lanChar.checkInvalidString
          },
          tcpUri: value => {
            const pattern = /^tcp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5}$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
          udpUri: value => {
            const pattern = /^udp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5}$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
          tcpUdpUri: value => {
            const pattern = /^tcp|udp:\/\/(([a-zA-Z\-0-9.]+))+\/[0-9]{1,5}$/
            return pattern.test(value) || this.lanChar.checkInvalidUri
          },
        },
        roleItems: [
          'server',
          'client',
        ],
        // snackbar data
        snackbarDescp: {
          snackbar: false,
          snackbarContent: 'snackbar content',
          snackbarTimeout: 2000,
          snackbarType: 'info',
        },
        // dialog data
        alert: {
          dialog: false,
          title: '',
          msg: '',
        },
        confirm: {
          dialog: false,
          content: {
            title: '',
            msg: '',
          },
          operate: {
            callback: null,
            input: null,
          },
        },
      }
    },
    watch: {
      dialog (val, oldVal) {
        if (val === oldVal) return

        this.$emit('input', val)
      },
      value (val, oldVal) {
        if (val === oldVal) return

        this.dialog = val
      },
      input: {
        handler (val, oldVal) {
          if (val === oldVal) return
          if (val.val !== null && val.val !== undefined && val.val.Name !== undefined) {
            this.groupRule = JSON.parse(JSON.stringify(val.val))
            this.groupRule.Clients.forEach(e => {
              e.Role = (e.Role === 0) ? 'server' : 'client'
            })
            this.groupRule.NameBak = this.groupRule.Name
          }
          this.mode = val.mode
        },
        deep: true,
      },
    },
    created () {
      globalDef.VueObject.$on('lanChange', lanChar => {
        this.lanChar = lanChar
      })
    },
    mounted () {
    },
    beforeDestroy () {
    },
    methods: {
      tipInfo (level, content, timeout) {
        this.snackbarDescp.snackbarType = level
        this.snackbarDescp.snackbarContent = content
        this.snackbarDescp.snackbarTimeout = timeout
        this.snackbarDescp.snackbar = true
      },
      alertInfo (title, content) {
        this.alert.dialog = true
        this.alert.title = title
        this.alert.msg = content
      },
      confirmDialog (title, msg, operate, data) {
        this.confirm.content.title = title
        this.confirm.content.msg = msg
        this.confirm.operate.callback = operate
        this.confirm.operate.input = data
        this.confirm.dialog = true
      },
      addClientUri () {
        this.groupRule.Clients.push({
          Uri: 'tcp://teminal-ip/port',
        })
      },
      getGroupRule () {
        const data = {
          request_type: 'mc group rule get',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            Name: this.groupRule.Name,
          },
        }
        mcAxios.axiosGetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.groupRule = res.data.data
              this.groupRule.Clients.forEach(e => {
                e.Role = (e.Role === 0) ? 'server' : 'client'
              })
              this.groupRule.NameBak = this.groupRule.Name
            } else {
              console.log('getGroupRule get res fail')
            }
          })
          .catch((e) => {
            console.log('getGroupRule get fail: ', e)
          })
      },
      applyAdd () {
        if ((String(this.groupRule.Name) === '')) {
          this.alertInfo(this.lanChar.alertInfoTitleInputError, this.lanChar.alertInfoParamError)
          return
        }
        const data = {
          request_type: 'mc group rule add',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: this.groupRule,
        }
        data.data.Clients.forEach(e => {
          e.Role = (e.Role === 'server') ? 0 : 1
        })
        mcAxios.axiosSetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.getGroupRule()
              this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
      applyModify () {
        if ((String(this.groupRule.Name) === '') || (String(this.groupRule.NameBak) === '')) {
          this.alertInfo(this.lanChar.alertInfoTitleInputError, this.lanChar.alertInfoParamError)
          return
        }
        const dataDel = {
          request_type: 'mc group rule del',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            Name: this.groupRule.NameBak,
          },
        }
        mcAxios.axiosSetConfig(dataDel)
          .then((res) => {
            if (res.data.status === true) {
              const dataAdd = {
                request_type: 'mc group rule add',
                instance_id: 'instance_id',
                sequence_no: 1000,
                data: this.groupRule,
              }
              dataAdd.data.Clients.forEach(e => {
                e.Role = (e.Role === 'server') ? 0 : 1
              })
              mcAxios.axiosSetConfig(dataAdd)
                .then((res) => {
                  if (res.data.status === true) {
                    this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
                  } else {
                    this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
                  }
                  this.getGroupRule()
                })
                .catch((e) => {
                  this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
                })
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
    },
  }
</script>
